import {PROMISE,BLOB,URL} from 'oneutil'
import CameraFrameListener from './CameraFrameListener'

export default class CameraContext {
  constructor(cameraContext) {
    this.n = 0
    this.recordedChunks = []
    this.cameraContext = cameraContext[0]
  }

  _logger() {
    this.timer = setInterval(() => {
      this.n += 1
    }, 1000)
  }

  setZoom(wx_objct) {
    const { success, fail, complete } = wx_objct

    PROMISE(SUCCESS => {
      SUCCESS({ errMsg: 'html is not support setzoom !' })
    }, success, fail, complete)
  }

  startRecord(wx_object) {
    const { timeoutCallback, success, fail, complete } = wx_object
    PROMISE(SUCCESS => {
      this._logger()
      let recordedChunks = []
      const stream = window.onekit_camera_stream
      this.mediaRecorder = new MediaRecorder(stream)
      this.mediaRecorder.start()

      this.mediaRecorder.addEventListener("dataavailable", function (e) {
        if (e.data.size > 0) recordedChunks.push(e.data)
      })

      this.mediaRecorder.addEventListener('stop', () => {

        this.stop_callback(recordedChunks)
      })

      if (this.n > 30) timeoutCallback()

      SUCCESS()
    }, success, fail, complete)
  }

  stopRecord(wx_object) {
    const { /*compressed,*/ success, fail, complete } = wx_object
    PROMISE(SUCCESS => {
      clearInterval(this.timer)

      if (this.mediaRecorder && this.mediaRecorder.state == 'recording') {
        this.mediaRecorder.stop()

        this.stop_callback = function (chunks) {

          const blob = new Blob(chunks, { type: "application/video" })
          const tempVideoPath = URL.createObjectURL(blob)
          const size = blob.size
  
          BLOB.blob2Base64(blob, base64 => {
            const res = {
              duration: this.n,
              errMsg: 'operateCamera: ok',
              height: this.cameraContext.videoHeight,
              size,
              tempThumPath: base64,
              tempVideoPath,
              width: this.cameraContext.videoWidth
            }

            SUCCESS(res)
            this.n = 0
          })


        }

      } else {
        console.log('还没有开始')
      }


    }, success, fail, complete)
  }

  takePhoto(wx_objct) {
    const {  success, fail, complete } = wx_objct
    PROMISE(SUCCESS => {
      const canvas = document.createElement('canvas')
      canvas.style.width = 480
      canvas.style.height = 320
      const context = canvas.getContext('2d')
      context.drawImage(this.cameraContext, 0, 0, 235, 135)
      const url = canvas.toDataURL('image/jpg')
      const tempImagePath = url
      const res = {
        errMsg: 'takephoto: ok',
        tempImagePath
      }

      SUCCESS(res)
    }, success, fail, complete)

  }
  onCameraFrame(callback) {
    callback({ data: '', height: this.cameraContext.videoHeight, width: this.cameraContext.videoWidth })
    return new CameraFrameListener()
  }
}
